using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;

namespace Agricultural_Sales.ASP
{
    public partial class ProductDetail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 检查是否有商品ID参数
                if (Request.QueryString["id"] == null)
                {
                    Response.Redirect("Home.aspx");
                    return;
                }

                // 验证商品ID是否为有效数字
                if (!int.TryParse(Request.QueryString["id"], out int productId))
                {
                    Response.Redirect("Home.aspx");
                    return;
                }
            }
        }

        protected void ProductAction_Command(object sender, CommandEventArgs e)
        {
            string productId = e.CommandArgument.ToString();

            switch (e.CommandName)
            {
                case "AddToCart":
                    // 添加到购物车逻辑
                    AddToCart(productId);
                    break;

                case "BuyNow":
                    // 立即购买逻辑
                    BuyNow(productId);
                    break;
            }
        }

        private void AddToCart(string productId)
        {
            try
            {
                // 检查用户是否登录
                if (Session["UserId"] == null)
                {
                    string loginScript = "alert('请先登录后再添加到购物车'); window.location.href='Login.aspx?returnUrl=' + encodeURIComponent(window.location.href);";
                    ClientScript.RegisterStartupScript(this.GetType(), "LoginRequired", loginScript, true);
                    return;
                }

                // 这里可以实现添加到购物车的逻辑
                // 例如：将商品ID存储到Session或数据库中

                // 模拟添加到购物车的逻辑
                List<string> cart = Session["Cart"] as List<string> ?? new List<string>();
                cart.Add(productId);
                Session["Cart"] = cart;

                // 使用更美观的JavaScript提示
                string successScript = @"
                    showSuccessMessage('商品已成功添加到购物车！');
                    // 可以在这里添加更多的交互效果
                    $('.btn-add-cart').css('background', 'linear-gradient(45deg, #27ae60, #2ecc71)');
                ";

                ClientScript.RegisterStartupScript(this.GetType(), "AddToCart", successScript, true);
            }
            catch (Exception ex)
            {
                // 错误处理
                string errorScript = $"showErrorMessage('添加到购物车失败：{ex.Message}');";
                ClientScript.RegisterStartupScript(this.GetType(), "AddToCartError", errorScript, true);
            }
        }

        private void BuyNow(string productId)
        {
            try
            {
                // 检查用户是否登录
                if (Session["UserId"] == null)
                {
                    string loginScript = "alert('请先登录后再购买商品'); window.location.href='Login.aspx?returnUrl=' + encodeURIComponent(window.location.href);";
                    ClientScript.RegisterStartupScript(this.GetType(), "LoginRequired", loginScript, true);
                    return;
                }

                // 这里可以实现立即购买的逻辑
                // 例如：跳转到订单页面或结算页面

                // 使用更美观的JavaScript提示和跳转
                string buyScript = @"
                    showSuccessMessage('正在为您跳转到购买页面...');
                    setTimeout(function() {
                        // 这里可以跳转到实际的购买页面
                        // window.location.href = 'Checkout.aspx?productId=" + productId + @"';
                        alert('购买功能开发中，商品ID: " + productId + @"');
                    }, 1500);
                ";

                ClientScript.RegisterStartupScript(this.GetType(), "BuyNow", buyScript, true);
            }
            catch (Exception ex)
            {
                // 错误处理
                string errorScript = $"showErrorMessage('购买失败：{ex.Message}');";
                ClientScript.RegisterStartupScript(this.GetType(), "BuyNowError", errorScript, true);
            }
        }

        // 订单数据类
        public class OrderData
        {
            public int ProductId { get; set; }
            public string ProductName { get; set; }
            public int Quantity { get; set; }
            public decimal UnitPrice { get; set; }
            public decimal TotalAmount { get; set; }
            public string DeliveryAddress { get; set; }
            public string ContactPhone { get; set; }
            public string PaymentMethod { get; set; }
            public string PaymentStatus { get; set; }
        }

        protected void btnSubmitOrder_Click(object sender, EventArgs e)
        {
            try
            {
                // 检查用户是否登录
                if (Session["UserId"] == null)
                {
                    string script = "alert('请先登录后再提交订单'); window.location.href='Login.aspx?returnUrl=' + encodeURIComponent(window.location.href);";
                    ClientScript.RegisterStartupScript(this.GetType(), "LoginRequired", script, true);
                    return;
                }

                // 获取用户ID
                int userId = Convert.ToInt32(Session["UserId"]);

                // 解析订单数据
                string orderDataJson = hdnOrderData.Value;
                if (string.IsNullOrEmpty(orderDataJson))
                {
                    throw new Exception("订单数据为空");
                }

                OrderData orderData = JsonConvert.DeserializeObject<OrderData>(orderDataJson);

                // 验证库存
                if (!ValidateInventory(orderData.ProductId, orderData.Quantity))
                {
                    string script = "showErrorMessage('库存不足，无法完成订单'); closePurchaseModal();";
                    ClientScript.RegisterStartupScript(this.GetType(), "InventoryError", script, true);
                    return;
                }

                // 创建订单
                int orderId = CreateOrder(userId, orderData);

                if (orderId > 0)
                {
                    // 创建支付记录
                    CreatePayment(orderId, orderData);

                    // 创建订单商品关联
                    CreateOrderProduct(orderId, orderData.ProductId);

                    // 更新库存
                    UpdateInventory(orderData.ProductId, orderData.Quantity);

                    // 成功提示
                    string script = $@"
                        closePurchaseModal();
                        showSuccessMessage('订单创建成功！订单号：{orderId}');
                        setTimeout(function() {{
                            window.location.href = 'MyOrder.aspx';
                        }}, 2000);
                    ";
                    ClientScript.RegisterStartupScript(this.GetType(), "OrderSuccess", script, true);
                }
                else
                {
                    throw new Exception("订单创建失败");
                }
            }
            catch (Exception ex)
            {
                string script = $"showErrorMessage('订单创建失败：{ex.Message}'); closePurchaseModal();";
                ClientScript.RegisterStartupScript(this.GetType(), "OrderError", script, true);
            }
        }

        // 验证库存
        private bool ValidateInventory(int productId, int quantity)
        {
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string sql = "SELECT Inventory FROM Product WHERE ProductId = @ProductId";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@ProductId", productId);

                conn.Open();
                object result = cmd.ExecuteScalar();

                if (result != null)
                {
                    int inventory = Convert.ToInt32(result);
                    return inventory >= quantity;
                }

                return false;
            }
        }

        // 创建订单
        private int CreateOrder(int userId, OrderData orderData)
        {
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string sql = @"
                    INSERT INTO [Order] (UserId, OrderNum, OrderState, TotalAmout, DeliveryAddr, ContactPhone, UpdateAt)
                    VALUES (@UserId, @OrderNum, @OrderState, @TotalAmount, @DeliveryAddr, @ContactPhone, @UpdateAt);
                    SELECT SCOPE_IDENTITY();
                ";

                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@UserId", userId);
                cmd.Parameters.AddWithValue("@OrderNum", orderData.Quantity);

                // 根据支付状态设置订单状态
                string orderState = orderData.PaymentStatus == "立即支付" ? "已支付" : "待支付";
                cmd.Parameters.AddWithValue("@OrderState", orderState);

                cmd.Parameters.AddWithValue("@TotalAmount", orderData.TotalAmount);
                cmd.Parameters.AddWithValue("@DeliveryAddr", orderData.DeliveryAddress);
                cmd.Parameters.AddWithValue("@ContactPhone", orderData.ContactPhone);
                cmd.Parameters.AddWithValue("@UpdateAt", DateTime.Now);

                conn.Open();
                object result = cmd.ExecuteScalar();

                return result != null ? Convert.ToInt32(result) : 0;
            }
        }

        // 创建支付记录
        private void CreatePayment(int orderId, OrderData orderData)
        {
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string sql = @"
                    INSERT INTO Payment (OrderId, PayMethod, PayAmout, PayState, PayTime)
                    VALUES (@OrderId, @PayMethod, @PayAmount, @PayState, @PayTime)
                ";

                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@OrderId", orderId);
                cmd.Parameters.AddWithValue("@PayMethod", orderData.PaymentMethod);
                cmd.Parameters.AddWithValue("@PayAmount", orderData.TotalAmount);

                // 根据支付状态设置支付状态
                string payState = orderData.PaymentStatus == "立即支付" ? "支付成功" : "未支付";
                cmd.Parameters.AddWithValue("@PayState", payState);

                cmd.Parameters.AddWithValue("@PayTime", DateTime.Now);

                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }

        // 创建订单商品关联
        private void CreateOrderProduct(int orderId, int productId)
        {
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string sql = @"
                    INSERT INTO OrderProduct (OrderId, ProductId)
                    VALUES (@OrderId, @ProductId)
                ";

                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@OrderId", orderId);
                cmd.Parameters.AddWithValue("@ProductId", productId);

                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }

        // 更新库存
        private void UpdateInventory(int productId, int quantity)
        {
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string sql = @"
                    UPDATE Product 
                    SET Inventory = Inventory - @Quantity 
                    WHERE ProductId = @ProductId AND Inventory >= @Quantity
                ";

                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@ProductId", productId);
                cmd.Parameters.AddWithValue("@Quantity", quantity);

                conn.Open();
                int rowsAffected = cmd.ExecuteNonQuery();

                if (rowsAffected == 0)
                {
                    throw new Exception("库存更新失败，可能库存不足");
                }
            }
        }
    }
}